<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\RoomInfoVail;
use App\Http\Controllers\Validator\RoomWordbookVail;
use App\Model\Account\SystemType;
use App\Model\Backstage\RoomWordbook;
use App\Model\Backstage\RoomWordbookInfo;
use App\Tool\Error;
use Illuminate\Http\Request;
use Validator;
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header('Access-Control-Allow-Methods:GET, POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with, content-type');

/**
 * Class RoomWordbookController
 * @package App\Http\Controllers\Backstage
 * 房源楼盘字典控制器
 * date:2018-4-29
 */
class RoomWordbookController extends Controller
{

    /*
     * 楼盘字典添加时下拉框类型字段
     */
    public function wordType(){
        $data = [
            'metro' => RoomWordbook::$metro_arr,  //地铁数组
            'ring'  => RoomWordbook::$ring_arr,    //环线数据
            'structure' => RoomWordbook::$structure_arr,   //结构
            'land'   => RoomWordbook::$land_arr,          //土地
            'wall'   => RoomWordbook::$wall_arr          //外墙
        ];
//        $transaction = SystemType::storageRedis(1);
//        if (!$transaction) {
//            $data['transaction'] = '';
//        }
//        $data['transaction'] = $transaction;
//
//        $status = SystemType::storageRedis(204);
//        if (!$status) {
//            $data['status'] = '';
//        }
//        $data['status'] = $status;

        $data['transaction'] = SystemType::storageRedis(1);
        /**
         * 类型
         */
        //《住宅、商住、其他》--- 类型 204
        $data['zsq_type'] =  SystemType::storageRedis(204);

        //《商铺  铺厂 网点》----类型 237
        $data['spw_type'] =  SystemType::storageRedis(237);

        //《写字楼  写厂》-----类型  277
        $data['xx_type'] =  SystemType::storageRedis(277);

        //厂房 仓库-----类型  362
        $data['cc_type'] =  SystemType::storageRedis(362);

        //地皮-----类型  369
        $data['dp_type'] =  SystemType::storageRedis(369);

        //车位---------类型  394
        $data['c_type'] =  SystemType::storageRedis(394);
        return $this->success('ok',$data);
    }

    /**
     * @param Request $request
     * @param RoomWordbook $roomWordbook
     * @return \Illuminate\Http\JsonResponse
     * 查询所有楼盘字典
     */
    public function listBook(Request $request, RoomWordbook $roomWordbook){
        $keywords = '';
        if($request->input('keywords')){
            $keywords = $request->input('keywords');
        }
        $map['w_is_del'] = 1;
        $list = $roomWordbook->selectWordbook(env('PAGE_LIMIT_ADMIN'), $map, $keywords);
        if(!$list){
            return $this->error(Error::NULL_DATA);
        }
        foreach($list as $k => $v){
           $v->w_metro_name     = RoomWordbook::$metro_arr[$v->w_metro_id];
           $v->w_ring_name      = RoomWordbook::$ring_arr[$v->w_ring_id];
           $v->w_structure_name = RoomWordbook::$structure_arr[$v->w_structure];
           $v->w_w_land         = RoomWordbook::$land_arr[$v->w_land];
           $v->w_wall_name      = RoomWordbook::$wall_arr[$v->w_wall_id];
            $v->w_province_name = AreaController::getAreaName($v->w_province_id);
            $v->w_city_name = AreaController::getAreaName($v->w_city_id);
//            $v->w_area_name = AreaController::getAreaName($v->w_area_id);
            $v->w_purpose_name = SystemType::getTypeDetail($v->w_purpose_id);
            $v->w_type_name = SystemType::getTypeDetail($v->w_type_id);
        }
        return $this->success('ok', $list);
    }

    /**
     *添加楼盘字典
     * except
     */
    public function insertBook(Request $request, RoomWordbook $roomWordbook){
        $param = $request->except('token');
        $validator = RoomWordbookVail::validate($param);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $param['w_province_id'] = $this->province_code;
        $param['w_city_id']     = $this->city_code;
        $res =  $roomWordbook->insertWordbook($param); //插入数据
        if ($res === -1) {
            return $this->error(Error::REPEATED_PROPERTY);//楼盘字典名字重复不能添加
        }
        if($res){
            return $this->success('ok');
        }
        return $this->error(Error::ADD_ERROR);
    }

    /**
     * @param Request $request
     * @param RoomWordbook $roomWordbook
     * @return \Illuminate\Http\JsonResponse
     * 删除楼盘字典  此处做软删除
     */
    public function delBook(Request $request, RoomWordbook $roomWordbook){
        if(!$request->input('id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomWordbook->delWordbook($request->input('id'));
        if($res === -1){
            return $this->error(Error::OPERATION_ERROR);
        }
        if($res){
            return $this->success('ok', '操作成功！');
        }
        return $this->error(Error::DEL_ERROR);
    }

    /**
     * 回收站的楼盘字典列表
     */
    public function RecycleBinWordbookList(Request $request, RoomWordbook $roomWordbook){
        $param = $request->all();
        $where = [];
        if($request->input('start_time')){
            $where[] = ['w_updated_at', '>=', strtotime($param['start_time'].' 00:00:00')];
        } else {
            $where[] = ['w_updated_at', '>=', strtotime(date('Y-m-d',strtotime('-3 month')).' 00:00:00')];
        }

        if($request->input('end_time')){
            $where[] = ['w_updated_at', '<=', strtotime($param['end_time'].' 23:59:59')];
        } else {
            $where[] = ['w_updated_at', '<=', time()];
        }

        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            //楼盘字典名称
            $keywords = trim($request->input('keywords'));
        }

        $list = $roomWordbook->recycleBinList(env('PAGE_LIMIT_ADMIN'),$where,$keywords);
        if (!$list) {
            $data['start'] = date('Y-m-d',strtotime('-3 month'));
            $data['end']  = date('Y-m-d',time());
            return $this->error(Error::NULL_DATA,$data);
        }
        $start = date('Y-m-d',strtotime('-3 month'));
        $end = date('Y-m-d',time());
        return $this->success('ok', $list,$start,$end);
    }


    /**
     * 修改楼盘字典信息
     */
    public function saveBook(Request $request, RoomWordbook $roomWordbook){
        $param = $request->except('token');
        $validator = RoomWordbookVail::validate($param);
        if (!$validator || !isset($param['w_id'])) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomWordbook->saveWordbook($param);
        if($res){
            return $this->success('ok', '修改成功！');
        }
        return $this->error(Error::EDIT_ERROR);
    }

    /**
     * @param Request $request
     * @param RoomWordbook $roomWordbook
     * @return \Illuminate\Http\JsonResponse
     * 根据楼盘字典的名称  获取该楼盘的ID
     */
    public function getBookId(Request $request, RoomWordbook $roomWordbook){
        if(!$request->input('w_name')){
            return $this->error(Error::PARAM_MISSING);
        }
        $name = $roomWordbook->getRoomId($request->input('w_name'));
        if (!$name) {
            return $this->error(Error::NO_PROPERTY);
        }
        return $this->success('ok', $name);
    }


    /**栋座添加时下拉框类型数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function wordBookType(){
        $data = [
            'building' => RoomWordbookInfo::$building_unit, //栋座名称单位
            'cell'  => RoomWordbookInfo::$cell_unit,    //单元数单位
        ];
        return $this->success('ok',$data);
    }


    /**
     * 添加楼盘字典-楼栋信息
     */
    public function addBuilding(Request $request, RoomWordbookInfo $roomWordbookInfo){
        $param = $request->except('token');
        if(!RoomWordbookVail::wordInfoValidate($param)){
            return $this->error(Error::PARAM_MISSING);
        }
        if (RoomWordbookInfo::$cell_unit[$param['b_cell_unit']] == '英文') {
            if (intval($param['b_cell_num']) > 26 || intval($param['b_cell_num']) < 1) {
                return $this->error(Error::OVERSIZE_TWO_SIX);
            }
        } else {
            if (intval($param['b_cell_num']) < 1) {
                return $this->error(Error::OVERSIZE_ZERO);
            }
        }
        $res = $roomWordbookInfo->addWordbookInfo($param);
        if($res){
            return $this->success('ok');
        }
        return $this->error(Error::ADD_ERROR);
    }

    /**
     * @param Request $request
     * @param RoomWordbookInfo $roomWordbookInfo
     * @return \Illuminate\Http\JsonResponse
     * 批量添加楼盘字典-栋座信息
     */
    public function batchAddBuilding(Request $request, RoomWordbookInfo $roomWordbookInfo){
        $param = $request->except('token');
        if(!RoomWordbookVail::batchWordInfoValidate($param)){
            return $this->error(Error::PARAM_MISSING);
        }

        if (RoomWordbookInfo::$cell_unit[$param['b_cell_unit']] == '英文') {
            if (intval($param['b_cell_num']) > 26 || intval($param['b_cell_num']) < 1) {
                return $this->error(Error::OVERSIZE_TWO_SIX);
            }
        } else {
            if (intval($param['b_cell_num']) < 1) {
                return $this->error(Error::OVERSIZE_ZERO);
            }
        }
        $res = $roomWordbookInfo->batchAddInfo($param);
        if ($res === -1) {
            return ['code'=> -301, 'msg' => '必须填写数字，且结束值必须大于开始值'];
        }
        if ($res === -2) {
            return ['code'=> -302, 'msg' => '一次最多创建'.env('BUILDING_LIMIT_ADMIN').'个'];
        }
        if ($res === -3) {
            return ['code'=> -303, 'msg' => '字母必须为a到z或者A-Z'];
        }
        if ($res === -4) {
            return ['code'=> -304, 'msg' => '字母须顺序填写！'];
        }
        if($res){
            return $this->success('ok', '添加成功');
        }
        return $this->error(Error::ADD_ERROR);
    }

    /**
     * @param Request $request
     * @param RoomWordbookInfo $roomWordbookInfo
     * @return \Illuminate\Http\JsonResponse
     * 修改楼盘字典 - 栋座信息
     */
    public function saveBuilding(Request $request, RoomWordbookInfo $roomWordbookInfo){
        $param = $request->except('token');
        if(!RoomWordbookVail::wordInfoValidate($param) || !isset($param['b_id']) || $param['b_id'] == ''){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomWordbookInfo->saveBuildingInfo($param);
        if($res){
            return $this->success('ok');
        }
        return $this->error(Error::EDIT_ERROR);
    }
    /**
     * @param Request $request
     * @param RoomWordbookInfo $roomWordbookInfo
     * @return \Illuminate\Http\JsonResponse
     * 删除楼盘字典 - 栋座信息
     */
    public function delBuilding(Request $request, RoomWordbookInfo $roomWordbookInfo){
        if(!$request->input('b_id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomWordbookInfo->delBuildingInfo($request->input('b_id'));
        if(!$res){
            return $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功！');
    }

    /**
     * @param Request $request
     * @param RoomWordbookInfo $roomWordbookInfo
     * @return \Illuminate\Http\JsonResponse
     * 查询楼盘字典 - 栋座信息列表
     */
    public function listBuilding(Request $request, RoomWordbookInfo $roomWordbookInfo){
        if(!$request->input('w_id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $map['b_w_id'] = $request->input('w_id');
        $list = $roomWordbookInfo->selectBuilding($map);
        if(!$list){
            return $this->error(Error::NULL_DATA);
        }
        foreach($list as $k => $v){
            $v->b_building_unit = RoomWordbookInfo::$building_unit[$v->b_building_unit];
            $v->b_cell_unit     = RoomWordbookInfo::$cell_unit[$v->b_cell_unit];
        }
        return $this->success('ok', $list);


    }



    /**
     * 添加房源时 搜索楼盘字典
     */
    public function searchBook(Request $request, RoomWordbook $roomWordbook){
        //楼盘字典
        $params = $request->except('token');
        $validator =  RoomInfoVail::getWordbookValidate($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $map['w_is_del'] = 1;
//        $map['w_province_id'] = $params['p_id']; //省
//        $map['w_city_id'] = $params['c_id'];  //市
        $list = $roomWordbook->getRoomWordbook($map, $params['w_spell']);
        if(sizeof($list) == 0){
            return $this->error(Error::NULL_DATA);
        }
        return $this->success('ok',$list);
    }

    /**添加房源的时候根据楼盘字典的名称获取高楼盘下的所有栋座
     * @param Request $request
     */
    public function getBuilding(Request $request,RoomWordbook $roomWordbook, RoomWordbookInfo $roomWordbookInfo)
    {
        $wName = $request->input('w_name');//楼盘字典的名称这里传的是汉字
        //1.根据楼盘名称查询该楼盘的ID  2.根据查询出来的楼盘ID 获取该楼盘下面的所有栋座信息
        $wId = $roomWordbook->getRoomId($wName);
        if (!$wId) {
            return $this->error(Error::NO_PROPERTY);//该楼盘不存在
        }
        $list = $roomWordbookInfo->selectBuildingforAdd($wId);
        return $this->success('ok', $list);
    }

    /**根据栋座的名称获取下面所有的单位信息
     * @param Request $request
     * @param RoomWordbookInfo $roomWordbookInfo
     */
    public function getPosition(Request $request, RoomWordbookInfo $roomWordbookInfo)
    {
        $building = $request->input('b_building');//栋座名称
        $b_w_id = $request->input('b_w_id');//楼盘ID
        $list = $roomWordbookInfo->getPositionInfo($building, $b_w_id);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        return $this->success('ok', $list);
    }

    /**
     * 回收站软删除 楼盘字典
     */
    public function delRecycleBook(Request $request, RoomWordbook $roomWordbook)
    {
        if(!$request->input('w_id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomWordbook->delRecycleBook($request->input('w_id'));
        if ($res === -1) {
            return $this->error(Error::DEL_ERROR);
        }
        if (!$res) {
            return $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功！');
    }

}